<?php

declare(strict_types=1);

namespace App\Controller;

use App\Constants\ErrorCode;
use App\Exception\BusinessException;
use App\Exception\NotFoundException;
use App\Exception\UnauthorizedException;
use App\Helper\ResponseHelper;
use Hyperf\Context\Context;

/**
 * 使用示例控制器
 */
class ExampleController extends AbstractController
{
    /**
     * 成功响应示例
     */
    public function success()
    {
        $data = [
            'id' => 1,
            'name' => 'John Doe',
            'email' => 'john@example.com',
        ];

        return ResponseHelper::success($data, 'User retrieved successfully');
    }

    /**
     * 失败响应示例
     */
    public function fail()
    {
        return ResponseHelper::fail('Operation failed', ErrorCode::BAD_REQUEST);
    }

    /**
     * 分页响应示例
     */
    public function paginate()
    {
        $items = [
            ['id' => 1, 'name' => 'Item 1'],
            ['id' => 2, 'name' => 'Item 2'],
            ['id' => 3, 'name' => 'Item 3'],
        ];

        return ResponseHelper::paginate(
            items: $items,
            total: 100,
            page: 1,
            pageSize: 15
        );
    }

    /**
     * 创建成功响应示例
     */
    public function create()
    {
        // 模拟创建操作
        return ResponseHelper::created('User created successfully');
    }

    /**
     * 未授权响应示例
     */
    public function unauthorized()
    {
        return ResponseHelper::unauthorized('Please login first');
    }

    /**
     * 抛出业务异常示例（会被全局异常处理器捕获）
     */
    public function throwBusinessException()
    {
        // 方式 1：直接抛出
        throw new BusinessException(ErrorCode::USER_NOT_FOUND, 'User with ID 123 not found');
    }

    /**
     * 抛出未授权异常示例
     */
    public function throwUnauthorizedException()
    {
        throw new UnauthorizedException('Token is invalid or expired');
    }

    /**
     * 抛出未找到异常示例
     */
    public function throwNotFoundException()
    {
        throw new NotFoundException('The requested resource was not found');
    }

    /**
     * 使用静态方法抛出异常
     */
    public function throwStatic()
    {
        BusinessException::throw(ErrorCode::PERMISSION_DENIED, 'You do not have permission to access this resource');
    }

    /**
     * 模拟系统异常（未捕获的异常）
     */
    public function throwSystemException()
    {
        // 这会触发默认异常处理
        throw new \RuntimeException('This is a system error');
    }

    /**
     * 验证失败示例
     */
    public function validationError()
    {
        $errors = [
            'name' => ['The name field is required.'],
            'email' => ['The email field must be a valid email address.'],
        ];

        return ResponseHelper::validationError($errors);
    }

    /**
     * 完整业务逻辑示例
     */
    public function getUserById()
    {
        $id = $this->request->input('id');

        // 验证参数
        if (!$id) {
            return ResponseHelper::fail('User ID is required', ErrorCode::BAD_REQUEST);
        }

        // 模拟查询数据库
        if ($id != 1) {
            throw new NotFoundException("User with ID {$id} not found");
        }

        // 返回成功数据
        $user = [
            'id' => 1,
            'name' => 'John Doe',
            'email' => 'john@example.com',
            'created_at' => date('Y-m-d H:i:s'),
        ];

        return ResponseHelper::success($user, 'User retrieved successfully');
    }

    /**
     * 自定义 JSON 响应示例
     */
    public function customResponse()
    {
        return ResponseHelper::json(
            code: 0,
            message: 'Custom response',
            data: ['custom' => 'data'],
            httpCode: 200
        );
    }

    /**
     * 测试日志记录 - GET 请求
     */
    public function testLogGet()
    {
        $requestId = Context::get('request_id');
        
        return ResponseHelper::success([
            'request_id' => $requestId,
            'message' => 'GET 请求日志记录成功',
            'query_params' => $this->request->getQueryParams(),
        ]);
    }

    /**
     * 测试日志记录 - POST 请求（含敏感信息）
     */
    public function testLogPost()
    {
        $requestId = Context::get('request_id');
        $body = $this->request->all();
        
        return ResponseHelper::success([
            'request_id' => $requestId,
            'message' => 'POST 请求日志记录成功',
            'received_data' => $body,
            'note' => '敏感字段（如 password）在日志中已被脱敏',
        ]);
    }

    /**
     * 测试慢请求日志记录
     */
    public function testLogSlow()
    {
        $requestId = Context::get('request_id');
        
        // 模拟慢请求
        $delay = (int) $this->request->input('delay', 2);
        $delay = min($delay, 10); // 最多延迟 10 秒
        sleep($delay);
        
        return ResponseHelper::success([
            'request_id' => $requestId,
            'message' => "模拟慢请求，延迟 {$delay} 秒",
            'delay_seconds' => $delay,
        ]);
    }

    /**
     * 测试错误请求日志记录
     */
    public function testLogError()
    {
        $requestId = Context::get('request_id');
        
        // 抛出业务异常
        throw new BusinessException(
            '这是一个测试异常，用于验证异常日志记录',
            ErrorCode::BUSINESS_ERROR
        );
    }
}

